<template>
	<view class="schedule-container">
		<!-- 顶部状态栏 -->
		<view class="status-bar">
			<view class="app-title">
				<uni-icons type="calendar" size="20" color="#3B82F6"></uni-icons>
				<text class="title-text">我的课表</text>
			</view>
			<view class="status-info" v-if="hasSchedule">
				<text class="course-count">{{courseCount}}门课程</text>
			</view>
		</view>

		<!-- 导入课表区域 -->
		<view class="import-section" v-if="!hasSchedule">
			<view class="import-card">
				<view class="import-header">
					<view class="import-icon">
						<uni-icons type="cloud-download" size="60" color="#3B82F6"></uni-icons>
					</view>
					<view class="import-title">
						<text class="title">订阅课表</text>
						<text class="subtitle">从链接导入您的课程安排</text>
					</view>
				</view>

				<view class="simple-form">
					<view class="input-wrapper">
						<uni-icons type="link" size="18" color="#6B7280" />
					<input 
						class="simple-input" 
						type="text" 
						v-model="scheduleUrl"
						placeholder="请输入课表链接或内容"
						:disabled="isLoading"
					/>
						<uni-icons 
							v-if="scheduleUrl && !isLoading" 
							type="clear" 
							size="16" 
							color="#6B7280" 
							@click="clearInput"
						/>
					</view>
					
					<button 
						class="simple-btn" 
						@click="handleImportContent"
						:disabled="!scheduleUrl || isLoading"
					>
						{{isLoading ? '处理中...' : '导入课表'}}
					</button>
				</view>
			</view>
		</view>

		<!-- 课表内容区域 -->
		<view class="schedule-content" v-else>
			<!-- 简化的周导航 -->
			<view class="week-navigation-compact">
					<view class="week-info">
						<text class="week-title">第 {{currentWeekNumber}} 周</text>
						<text class="week-date">{{weekDateRange}}</text>
					</view>
					<view class="nav-actions">
						<button class="nav-btn" @click="goToPreviousWeek" :disabled="!canGoPrevious">
							<uni-icons type="left" size="14" color="#6B7280"></uni-icons>
						</button>
						<button class="nav-btn" @click="goToNextWeek" :disabled="!canGoNext">
							<uni-icons type="right" size="14" color="#6B7280"></uni-icons>
						</button>
					</view>
				</view>
				
			<!-- 课表网格 - 占据主要空间 -->
			<view class="schedule-grid-main">
				<!-- 时间轴 -->
				<view class="time-column">
					<view class="time-header">时间</view>
					<view 
						class="time-slot" 
						v-for="slot in timeSlots" 
						:key="slot.id"
						:style="{ height: slot.height + 'px' }"
					>
						<text class="time-label">{{slot.startTime}}</text>
						<text class="time-sub">{{slot.endTime}}</text>
					</view>
				</view>

				<!-- 日期列 -->
				<view class="days-container">
					<view class="days-wrapper">
						<view 
							class="day-column" 
							v-for="(day, index) in weekDays" 
							:key="index"
						>
							<view class="day-header" :class="{ 'today': day.isToday, 'weekend': day.isWeekend }">
								<text class="day-name">{{day.name}}</text>
								<text class="day-date">{{day.date}}</text>
								<view class="day-indicator" v-if="day.isToday"></view>
							</view>
							
							<view class="day-content">
								<!-- 按时间段显示课程 -->
								<view 
									class="time-slot-content" 
									v-for="slot in timeSlots" 
									:key="slot.id"
									:style="{ height: slot.height + 'px' }"
								>
									<view 
										class="course-item" 
										v-for="course in day.organizedCourses[slot.id]" 
										:key="course.id"
										:style="getCourseStyleWithPosition(course)"
										:class="{ 'spanning-course': course.isSpanning }"
										@click="showCourseDetail(course)"
									>
										<view class="course-header">
											<view class="course-title">{{course.title}}</view>
											<view class="span-indicator" v-if="course.isSpanning">
												<uni-icons type="arrowdown" size="8" color="#FFFFFF"></uni-icons>
											</view>
										</view>
										<view class="course-time">{{formatCourseTime(course)}}</view>
										<view class="course-location" v-if="course.location">
											<uni-icons type="location" size="10" color="#9CA3AF"></uni-icons>
											<text>{{course.location}}</text>
										</view>
										<view class="course-teacher" v-if="course.teacher">{{course.teacher}}</view>
									</view>
								</view>
								
								<!-- 空状态 -->
								<view class="empty-day" v-if="day.courses.length === 0">
									<uni-icons type="calendar" size="24" color="#E5E7EB"></uni-icons>
									<text>今日无课</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 底部功能区域 -->
			<view class="bottom-actions">
				<view class="action-buttons">
					<button class="action-btn secondary" @click="showSettingsPopup">
						<uni-icons type="gear" size="18" color="#6B7280"></uni-icons>
						<text>设置</text>
						<!-- 提醒状态指示器 -->
						<view class="reminder-indicator" v-if="reminderSettings.enabled">
							<uni-icons type="sound" size="8" color="#10B981"></uni-icons>
						</view>
					</button>
					<button class="action-btn secondary" @click="refreshSchedule">
						<uni-icons type="reload" size="18" color="#6B7280"></uni-icons>
						<text>刷新</text>
					</button>
					<button class="action-btn primary" @click="exportCurrentWeek">
						<uni-icons type="download" size="18" color="#FFFFFF"></uni-icons>
						<text>导出</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 课程详情弹窗 -->
		<SimplePopup ref="coursePopup" type="bottom">
			<view class="course-detail-modal">
				<view class="modal-header">
					<text class="modal-title">课程详情</text>
					<button class="close-btn" @click="closeCourseDetail">
						<uni-icons type="close" size="18" color="#9CA3AF"></uni-icons>
					</button>
				</view>
				
				<view class="course-details" v-if="selectedCourse">
					<view class="detail-row">
						<view class="detail-icon">
							<uni-icons type="book" size="16" color="#3B82F6"></uni-icons>
						</view>
						<view class="detail-content">
							<text class="detail-label">课程名称</text>
							<text class="detail-value">{{selectedCourse.title}}</text>
						</view>
					</view>
					
					<view class="detail-row" v-if="selectedCourse.teacher">
						<view class="detail-icon">
							<uni-icons type="person" size="16" color="#10B981"></uni-icons>
						</view>
						<view class="detail-content">
							<text class="detail-label">授课教师</text>
							<text class="detail-value">{{selectedCourse.teacher}}</text>
						</view>
					</view>
					
					<view class="detail-row">
						<view class="detail-icon">
							<uni-icons type="clock" size="16" color="#F59E0B"></uni-icons>
						</view>
						<view class="detail-content">
							<text class="detail-label">上课时间</text>
							<text class="detail-value">{{formatFullCourseTime(selectedCourse)}}</text>
						</view>
					</view>
					
					<view class="detail-row" v-if="selectedCourse.location">
						<view class="detail-icon">
							<uni-icons type="location" size="16" color="#EF4444"></uni-icons>
						</view>
						<view class="detail-content">
							<text class="detail-label">上课地点</text>
							<text class="detail-value">{{selectedCourse.location}}</text>
						</view>
					</view>
				</view>
			</view>
		</SimplePopup>

		<!-- 设置弹窗 -->
		<SimplePopup ref="settingsPopup" type="center">
			<view class="settings-modal">
				<view class="modal-header">
					<text class="modal-title">课表设置</text>
					<button class="close-btn" @click="closeSettings">
						<uni-icons type="close" size="18" color="#9CA3AF"></uni-icons>
					</button>
				</view>
				
				<view class="settings-content">
					<!-- 提醒设置 -->
					<view class="setting-section">
						<text class="section-title">上课提醒</text>
						
						<view class="setting-item">
							<view class="setting-info">
								<text class="setting-label">开启提醒</text>
								<text class="setting-desc">在上课前收到通知提醒</text>
							</view>
							<switch 
								:checked="reminderSettings.enabled" 
								@change="onReminderToggle"
								color="#3B82F6"
							/>
						</view>
						
						<view class="setting-item" v-if="reminderSettings.enabled">
							<view class="setting-info">
								<text class="setting-label">提醒时间</text>
								<text class="setting-desc">提前 {{reminderSettings.reminderMinutes}} 分钟提醒</text>
							</view>
							<picker 
								:value="reminderTimeIndex" 
								:range="reminderTimeOptions"
								range-key="label"
								@change="onReminderTimeChange"
							>
								<button class="setting-btn secondary">
									<text>{{reminderTimeOptions[reminderTimeIndex].label}}</text>
									<uni-icons type="right" size="12" color="#6B7280"></uni-icons>
								</button>
							</picker>
						</view>
						
						<view class="setting-item" v-if="reminderSettings.enabled && hasSchedule">
							<text class="setting-label">刷新提醒</text>
							<button class="setting-btn primary" @click="refreshReminders">
								<uni-icons type="reload" size="14" color="#FFFFFF"></uni-icons>
								<text>刷新</text>
							</button>
						</view>
					</view>
					
					<!-- 课表管理 -->
					<view class="setting-section">
						<text class="section-title">课表管理</text>
						
						<view class="setting-item">
							<text class="setting-label">重新订阅课表</text>
							<button class="setting-btn danger" @click="resubscribeSchedule">
								<uni-icons type="reload" size="14" color="#FFFFFF"></uni-icons>
								<text>重新订阅</text>
							</button>
						</view>
						
						<view class="setting-item">
							<text class="setting-label">清空课表数据</text>
							<button class="setting-btn danger" @click="clearAllData">
								<uni-icons type="trash" size="14" color="#FFFFFF"></uni-icons>
								<text>清空数据</text>
							</button>
						</view>
					</view>
				</view>
			</view>
		</SimplePopup>
	</view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { formatTime, formatDate } from '@/utils/icsParser.js'
import SimplePopup from '@/components/SimplePopup.vue'
import courseReminder from '@/utils/courseReminder.js'

export default {
	name: 'SchedulePage',
	components: {
		SimplePopup
	},
	
	data() {
		return {
			scheduleUrl: '',
			isLoading: false,
			selectedCourse: null,
			reminderSettings: {
				enabled: true,
				reminderMinutes: 30 // 统一使用30分钟默认值
			},
			
			// 提醒时间选项（统一使用全局设置）
			reminderTimeOptions: [
				{ value: 15, label: '15分钟前' },
				{ value: 30, label: '30分钟前' },
				{ value: 60, label: '1小时前' },
				{ value: 120, label: '2小时前' },
				{ value: 1440, label: '1天前' }
			],
			
			// 时间段配置 - 标准12节课，从08:30开始
			timeSlots: [
				{ id: 0, startTime: '08:30', endTime: '09:15', height: 45, label: '第1节' },
				{ id: 1, startTime: '09:25', endTime: '10:10', height: 45, label: '第2节' },
				{ id: 2, startTime: '10:30', endTime: '11:15', height: 45, label: '第3节' },
				{ id: 3, startTime: '11:25', endTime: '12:10', height: 45, label: '第4节' },
				{ id: 4, startTime: '13:30', endTime: '14:15', height: 45, label: '第5节' },
				{ id: 5, startTime: '14:25', endTime: '15:10', height: 45, label: '第6节' },
				{ id: 6, startTime: '15:20', endTime: '16:05', height: 45, label: '第7节' },
				{ id: 7, startTime: '16:25', endTime: '17:10', height: 45, label: '第8节' },
				{ id: 8, startTime: '17:20', endTime: '18:05', height: 45, label: '第9节' },
				{ id: 9, startTime: '19:00', endTime: '19:45', height: 45, label: '第10节' },
				{ id: 10, startTime: '19:55', endTime: '20:40', height: 45, label: '第11节' },
				{ id: 11, startTime: '20:50', endTime: '21:35', height: 45, label: '第12节' }
			]
		}
	},
	
	computed: {
		...mapState('courseSchedule', ['hasSchedule', 'allCourses']),
		...mapGetters('courseSchedule', [
			'currentWeekInfo',
			'currentWeekCourses',
			'allWeeks'
		]),
		
		courseCount() {
			return this.allCourses.length
		},
		
		currentWeekNumber() {
			return this.currentWeekInfo?.weekNumber || 1
		},
		
		weekDateRange() {
			if (!this.currentWeekInfo) return ''
			const start = formatDate(this.currentWeekInfo.weekStart)
			const end = formatDate(this.currentWeekInfo.weekEnd)
			return `${start} - ${end}`
		},
		
		weekDays() {
			if (!this.currentWeekInfo) return []
			
			const days = []
			const weekStart = new Date(this.currentWeekInfo.weekStart)
			const today = new Date()
			
			for (let i = 0; i < 7; i++) {
				const date = new Date(weekStart)
				date.setDate(date.getDate() + i)
				
				const dayIndex = date.getDay() === 0 ? 6 : date.getDay() - 1 // 转换为周一=0的格式
				const courses = this.getDayCourses(date.getDay())
				
				// 按时间段组织课程
				const organizedCourses = this.organizeCoursesInTimeSlots(courses)
				
				days.push({
					name: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][dayIndex],
					date: formatDate(date),
					isToday: this.isSameDay(date, today),
					isWeekend: dayIndex >= 5,
					courses: courses,
					organizedCourses: organizedCourses
				})
			}
			
			return days
		},
		
		canGoPrevious() {
			const weeks = this.allWeeks
			const currentIndex = weeks.findIndex(w => w.weekKey === this.currentWeekInfo?.weekKey)
			return currentIndex > 0
		},
		
		canGoNext() {
			const weeks = this.allWeeks
			const currentIndex = weeks.findIndex(w => w.weekKey === this.currentWeekInfo?.weekKey)
			return currentIndex < weeks.length - 1
		},
		
		// 提醒时间选择器当前索引
		reminderTimeIndex() {
			const index = this.reminderTimeOptions.findIndex(
				option => option.value === this.reminderSettings.reminderMinutes
			)
			return index >= 0 ? index : 2 // 默认选择15分钟前
		},
		
		// 下一个即将到来的课程
		nextUpcomingCourse() {
			if (!this.allCourses || this.allCourses.length === 0) return null
			
			const now = new Date()
			const upcomingCourses = this.allCourses
				.filter(course => course.startTime && new Date(course.startTime) > now)
				.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
			
			return upcomingCourses.length > 0 ? upcomingCourses[0] : null
		}

	},
	

	
	async onLoad() {
		this.loadScheduleData()
		this.restoreSavedUrl()
		
		// 初始化课程提醒服务
		try {
			await courseReminder.init()
			this.reminderSettings = courseReminder.getReminderSettings()
			
			// 如果有课程数据，设置提醒
			if (this.hasSchedule && this.reminderSettings.enabled) {
				await this.setupCourseReminders()
			}
		} catch (error) {
			console.error('初始化课程提醒失败:', error)
		}
	},
	
	onUnload() {
		// 页面卸载时停止实时检查器，避免内存泄漏
		courseReminder.stopRealTimeChecker()
	},
	
	methods: {
		...mapActions('courseSchedule', [
			'loadScheduleData',
			'importSchedule',
			'switchToPreviousWeek',
			'switchToNextWeek',
			'clearSchedule'
		]),
		
		// 导入课表内容
		async handleImportContent() {
			if (!this.scheduleUrl || !this.scheduleUrl.trim()) {
				this.showErrorMessage('请输入课表内容')
				return
			}
			
			this.isLoading = true
			
			try {
				let content = this.scheduleUrl.trim()
				
				// 如果输入的是URL，尝试获取内容
				if (this.isUrl(content)) {
					console.log('检测到URL，尝试获取内容:', content)
					content = await this.fetchScheduleContent(content)
				} else {
					console.log('直接使用输入的内容作为课表数据')
				}
				
				// 导入课表
				const result = await this.importSchedule(content)
				
				if (result.success) {
					uni.setStorageSync('scheduleUrl', this.scheduleUrl)
					this.showSuccessMessage(`成功导入 ${result.courseCount} 门课程`)
					
					// 导入成功后设置课程提醒
					if (this.reminderSettings.enabled) {
						await this.setupCourseReminders()
					}
				} else {
					// 显示详细的错误信息
					const errorMsg = this.getDetailedErrorMessage(result.error)
					this.showErrorMessage(errorMsg)
				}
			} catch (error) {
				console.error('导入失败:', error)
				this.showErrorMessage('导入失败: ' + error.message)
			} finally {
				this.isLoading = false
			}
		},
		
		// 简单判断是否为URL
		isUrl(str) {
			return str.startsWith('http://') || str.startsWith('https://') || str.startsWith('ftp://')
		},
		
		// 获取课表内容
		fetchScheduleContent(url) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: url,
					method: 'GET',
					timeout: 15000,
					success: (res) => {
						if (res.statusCode === 200) {
							resolve(res.data)
						} else {
							reject(new Error(`HTTP ${res.statusCode}`))
						}
					},
					fail: (error) => {
						reject(new Error('网络请求失败'))
					}
				})
			})
		},
		
		// 加载示例数据
		async loadDemoData() {
			// 这里可以加载一些示例课表数据
			this.showInfoMessage('示例功能开发中...')
		},
		
		// 周导航
		goToPreviousWeek() {
			if (this.canGoPrevious) {
				this.switchToPreviousWeek()
			}
		},
		
		goToNextWeek() {
			if (this.canGoNext) {
				this.switchToNextWeek()
			}
		},
		
		// 获取某天课程
		getDayCourses(weekday) {
			return this.$store.getters['courseSchedule/getDayCourses'](weekday)
		},
		
		// 按时间段组织课程
		organizeCoursesInTimeSlots(courses) {
			const organized = {}
			const processedCourses = new Set()
			
			// 初始化时间段
			this.timeSlots.forEach(slot => {
				organized[slot.id] = []
			})
			
			// 分析每门课程跨越的时间段
			courses.forEach(course => {
				if (!course.startTime || !course.endTime || processedCourses.has(course.id)) return
				
				const courseStartInMinutes = course.startTime.getHours() * 60 + course.startTime.getMinutes()
				const courseEndInMinutes = course.endTime.getHours() * 60 + course.endTime.getMinutes()
				
				// 找到课程跨越的所有时间段
				const spanningSlots = this.findSpanningTimeSlots(courseStartInMinutes, courseEndInMinutes)
				
				if (spanningSlots.length > 0) {
					// 创建跨时间段课程对象
					const spanningCourse = {
						...course,
						isSpanning: spanningSlots.length > 1,
						spanningSlots: spanningSlots,
						displaySlot: spanningSlots[0], // 在第一个时间段显示
						spanHeight: this.calculateSpanHeight(spanningSlots),
						timeSlotPosition: this.calculateSpanPosition(course, spanningSlots)
					}
					
					// 只在第一个时间段中添加课程
					organized[spanningSlots[0]].push(spanningCourse)
					processedCourses.add(course.id)
					
					// 在其他跨越的时间段中标记为占用（用于冲突检测）
					for (let i = 1; i < spanningSlots.length; i++) {
						organized[spanningSlots[i]].push({
							...course,
							isPlaceholder: true,
							originalSlot: spanningSlots[0]
						})
					}
				}
			})
			
			// 处理冲突课程的布局
			Object.keys(organized).forEach(slotId => {
				const slotCourses = organized[slotId].filter(c => !c.isPlaceholder)
				if (slotCourses.length > 1) {
					slotCourses.forEach((course, index) => {
						course.conflictIndex = index
						course.conflictCount = slotCourses.length
					})
				}
			})
			
			// 移除占位符
			Object.keys(organized).forEach(slotId => {
				organized[slotId] = organized[slotId].filter(c => !c.isPlaceholder)
			})
			
			return organized
		},
		
		// 找到课程跨越的时间段
		findSpanningTimeSlots(startMinutes, endMinutes) {
			const spanningSlots = []
			
			this.timeSlots.forEach(slot => {
				const [slotStartHour, slotStartMinute] = slot.startTime.split(':').map(Number)
				const [slotEndHour, slotEndMinute] = slot.endTime.split(':').map(Number)
				const slotStartInMinutes = slotStartHour * 60 + slotStartMinute
				const slotEndInMinutes = slotEndHour * 60 + slotEndMinute
				
				// 检查课程是否与此时间段有重叠
				if (startMinutes < slotEndInMinutes && endMinutes > slotStartInMinutes) {
					spanningSlots.push(slot.id)
				}
			})
			
			return spanningSlots.sort((a, b) => a - b)
		},
		
		// 计算跨时间段课程的高度
		calculateSpanHeight(spanningSlots) {
			let totalHeight = 0
			spanningSlots.forEach(slotId => {
				const slot = this.timeSlots.find(s => s.id === slotId)
				if (slot) {
					totalHeight += slot.height
				}
			})
			return totalHeight
		},
		
		// 计算跨时间段课程的位置
		calculateSpanPosition(course, spanningSlots) {
			const firstSlot = this.timeSlots.find(s => s.id === spanningSlots[0])
			const lastSlot = this.timeSlots.find(s => s.id === spanningSlots[spanningSlots.length - 1])
			
			if (!firstSlot || !lastSlot) return { top: 5, height: 90 }
			
			const courseStartInMinutes = course.startTime.getHours() * 60 + course.startTime.getMinutes()
			const courseEndInMinutes = course.endTime.getHours() * 60 + course.endTime.getMinutes()
			
			const [firstSlotStartHour, firstSlotStartMinute] = firstSlot.startTime.split(':').map(Number)
			const firstSlotStartInMinutes = firstSlotStartHour * 60 + firstSlotStartMinute
			
			// 计算在第一个时间段内的偏移
			const offsetInFirstSlot = Math.max(0, courseStartInMinutes - firstSlotStartInMinutes)
			const firstSlotDuration = 45 // 大部分时间段都是45分钟
			const topPercent = Math.max(2, (offsetInFirstSlot / firstSlotDuration) * 90 + 5)
			
			// 计算总的跨越高度（像素）
			const totalSpanHeight = this.calculateSpanHeight(spanningSlots)
			const courseDuration = courseEndInMinutes - courseStartInMinutes
			
			// 如果课程跨越多个时间段，使用实际的跨越高度
			if (spanningSlots.length > 1) {
				return {
					top: topPercent,
					height: totalSpanHeight - 10, // 减去一些边距
					isAbsolute: true // 标记为绝对高度（像素）
				}
			}
			
			// 单个时间段内的课程
			const heightPercent = Math.max(40, (courseDuration / firstSlotDuration) * 90)
			return {
				top: topPercent,
				height: Math.min(heightPercent, 95 - topPercent)
			}
		},
		
		// 计算课程在时间段中的位置
		calculateTimeSlotPosition(course, slotId) {
			const slot = this.timeSlots.find(s => s.id === slotId)
			if (!slot || !course.startTime) return { top: 5, height: 90 }
			
			const [slotStartHour, slotStartMinute] = slot.startTime.split(':').map(Number)
			const [slotEndHour, slotEndMinute] = slot.endTime.split(':').map(Number)
			
			const courseStartHour = course.startTime.getHours()
			const courseStartMinute = course.startTime.getMinutes()
			const courseEndHour = course.endTime ? course.endTime.getHours() : courseStartHour + 1
			const courseEndMinute = course.endTime ? course.endTime.getMinutes() : courseStartMinute + 45
			
			const slotStartInMinutes = slotStartHour * 60 + slotStartMinute
			const slotEndInMinutes = slotEndHour * 60 + slotEndMinute
			const courseStartInMinutes = courseStartHour * 60 + courseStartMinute
			const courseEndInMinutes = courseEndHour * 60 + courseEndMinute
			
			const slotDurationInMinutes = slotEndInMinutes - slotStartInMinutes
			
			// 如果课程在此时间段内
			if (courseStartInMinutes >= slotStartInMinutes && courseStartInMinutes < slotEndInMinutes) {
				const offsetFromSlotStart = courseStartInMinutes - slotStartInMinutes
				const courseDurationInSlot = Math.min(courseEndInMinutes, slotEndInMinutes) - courseStartInMinutes
				
				const topPercent = Math.max(2, (offsetFromSlotStart / slotDurationInMinutes) * 90 + 5)
				const heightPercent = Math.max(40, (courseDurationInSlot / slotDurationInMinutes) * 90)
				
				return {
					top: topPercent,
					height: Math.min(heightPercent, 95 - topPercent)
				}
			}
			
			// 默认占满大部分空间
			return {
				top: 5,
				height: 90
			}
		},
		
		// 课程样式
		getCourseStyle(course) {
			const color = course.color || this.generateCourseColor(course.title)
			
			return {
				backgroundColor: color + '20',
				borderLeftColor: color,
				borderLeftWidth: '3px',
				borderLeftStyle: 'solid'
			}
		},
		
		// 课程样式（包含位置信息）
		getCourseStyleWithPosition(course) {
			const baseStyle = this.getCourseStyle(course)
			const position = course.timeSlotPosition || { top: 0, height: 100 }
			
			// 处理冲突课程的并排显示
			let width = '100%'
			let left = '0%'
			
			if (course.conflictCount > 1) {
				width = (100 / course.conflictCount) + '%'
				left = (100 / course.conflictCount * course.conflictIndex) + '%'
			}
			
			// 处理跨时间段课程
			let height = position.height + '%'
			let zIndex = course.isSpanning ? 10 : 1 // 跨时间段课程层级更高
			
			if (position.isAbsolute) {
				height = position.height + 'px' // 使用绝对高度
			}
			
			// 跨时间段课程的特殊样式
			const extraStyles = {}
			if (course.isSpanning) {
				extraStyles.border = '2px solid ' + (course.color || this.generateCourseColor(course.title))
				extraStyles.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)'
			}
			
			return {
				...baseStyle,
				...extraStyles,
				position: 'absolute',
				top: position.top + '%',
				height: height,
				width: width,
				left: left,
				zIndex: zIndex
			}
		},
		
		// 生成课程颜色
		generateCourseColor(title) {
			const colors = [
				'#3B82F6', '#10B981', '#F59E0B', '#EF4444', 
				'#8B5CF6', '#06B6D4', '#F97316', '#EC4899'
			]
			return colors[Math.abs(title.length) % colors.length]
		},
		
		// 显示课程详情
		showCourseDetail(course) {
			this.selectedCourse = course
			this.$refs.coursePopup.open()
		},
		
		closeCourseDetail() {
			this.$refs.coursePopup.close()
			this.selectedCourse = null
		},
		
		// 设置相关
		showSettingsPopup() {
			this.$refs.settingsPopup.open()
		},
		
		closeSettings() {
			this.$refs.settingsPopup.close()
		},
		
		// 重新订阅
		resubscribeSchedule() {
			this.closeSettings()
			
			uni.showModal({
				title: '重新订阅',
				content: '将清空当前课表和提醒并重新从链接获取数据，确定继续吗？',
				success: async (res) => {
					if (res.confirm) {
						// 清除所有提醒
						await courseReminder.clearAllReminders()
						
						// 清空课表数据
						this.clearSchedule()
						this.restoreSavedUrl()
					}
				}
			})
		},
		
		// 清空数据
		clearAllData() {
			this.closeSettings()
			
			uni.showModal({
				title: '清空数据',
				content: '将删除所有课表数据和提醒，此操作不可恢复，确定继续吗？',
				success: async (res) => {
					if (res.confirm) {
						// 清除所有提醒
						await courseReminder.clearAllReminders()
						
						// 清空课表数据
						this.clearSchedule()
						uni.removeStorageSync('scheduleUrl')
						this.scheduleUrl = ''
						this.showSuccessMessage('数据已清空')
					}
				}
			})
		},
		
		// 刷新课表
		async refreshSchedule() {
			const savedUrl = uni.getStorageSync('scheduleUrl')
			if (savedUrl) {
				this.scheduleUrl = savedUrl
				await this.handleImportContent()
			} else {
				this.showInfoMessage('没有保存的课表链接')
			}
		},
		
		// 导出当前周
		exportCurrentWeek() {
			this.showInfoMessage('导出功能开发中...')
		},
		
		// 恢复保存的URL
		restoreSavedUrl() {
			const savedUrl = uni.getStorageSync('scheduleUrl')
			if (savedUrl) {
				this.scheduleUrl = savedUrl
			}
		},
		
		// 清除输入框
		clearInput() {
			this.scheduleUrl = ''
		},
		
		// 获取详细错误信息
		getDetailedErrorMessage(error) {
			if (!error) return '导入失败'
			
			const errorMsg = error.toString()
			
			if (errorMsg.includes('ICS文件内容无效')) {
				return '请输入有效的课表链接或ICS文件内容'
			} else if (errorMsg.includes('无效的ICS文件格式')) {
				return '文件格式不正确，请确保是有效的ICS日历文件'
			} else if (errorMsg.includes('未找到有效的课程事件')) {
				return '文件中没有找到课程信息，请检查文件内容'
			} else if (errorMsg.includes('网络请求失败')) {
				return '网络连接失败，请检查网络连接后重试'
			} else if (errorMsg.includes('HTTP')) {
				return '无法访问课表链接，请检查链接是否正确'
			} else {
				return `导入失败: ${errorMsg}`
			}
		},
		
		// 工具方法
		isSameDay(date1, date2) {
			return date1.getFullYear() === date2.getFullYear() &&
				   date1.getMonth() === date2.getMonth() &&
				   date1.getDate() === date2.getDate()
		},
		
		formatCourseTime(course) {
			const start = formatTime(course.startTime)
			const end = formatTime(course.endTime)
			return `${start}-${end}`
		},
		
		formatFullCourseTime(course) {
			const start = formatTime(course.startTime)
			const end = formatTime(course.endTime)
			const duration = Math.round((course.endTime - course.startTime) / (1000 * 60))
			return `${start} - ${end} (${duration}分钟)`
		},
		
		formatCourseDuration(course) {
			if (!course.endTime) return ''
			const duration = Math.round((course.endTime - course.startTime) / (1000 * 60))
			return `${duration}分钟`
		},
		
		// 消息提示
		showSuccessMessage(title) {
			uni.showToast({ title, icon: 'success', duration: 2000 })
		},
		
		showErrorMessage(title) {
			uni.showToast({ title, icon: 'none', duration: 3000 })
		},
		
		showInfoMessage(title) {
			uni.showToast({ title, icon: 'none', duration: 2000 })
		},
		
		// ==================== 课程提醒相关方法 ====================
		
		/**
		 * 设置课程提醒
		 */
		async setupCourseReminders() {
			if (!this.hasSchedule || !this.reminderSettings.enabled) {
				// 如果提醒被禁用，停止实时检查器
				courseReminder.stopRealTimeChecker()
				return
			}
			
			try {
				const result = await courseReminder.updateReminders(this.allCourses)
				console.log('课程提醒设置完成:', result)
				
				// 显示设置结果
				if (result && result.count > 0) {
					this.showSuccessMessage(`实时提醒已启动，监控 ${result.count} 门课程`)
				} else {
					this.showSuccessMessage('实时提醒已启动')
				}
			} catch (error) {
				console.error('设置课程提醒失败:', error)
				this.showErrorMessage('设置课程提醒失败')
			}
		},
		
		/**
		 * 切换提醒开关
		 */
		async toggleReminder(enabled) {
			this.reminderSettings.enabled = enabled
			courseReminder.saveReminderSettings(this.reminderSettings)
			
			if (enabled && this.hasSchedule) {
				// 开启提醒，重新设置所有提醒
				await this.setupCourseReminders()
			} else if (!enabled) {
				// 关闭提醒，清除所有提醒
				await courseReminder.clearAllReminders()
				this.showInfoMessage('已关闭课程提醒')
			}
		},
		
		/**
		 * 更新提醒时间
		 */
		async updateReminderTime(minutes) {
			this.reminderSettings.reminderMinutes = minutes
			courseReminder.saveReminderSettings(this.reminderSettings)
			
			if (this.reminderSettings.enabled && this.hasSchedule) {
				// 重新设置提醒
				await this.setupCourseReminders()
				this.showSuccessMessage(`提醒时间已更新为提前 ${minutes} 分钟`)
			}
		},
		
		/**
		 * 手动刷新提醒
		 */
		async refreshReminders() {
			if (!this.hasSchedule) {
				this.showInfoMessage('没有课程数据')
				return
			}
			
			try {
				await this.setupCourseReminders()
				this.showSuccessMessage('课程提醒已刷新')
			} catch (error) {
				console.error('刷新课程提醒失败:', error)
				this.showErrorMessage('刷新提醒失败')
			}
		},
		
		/**
		 * 提醒开关切换事件
		 */
		onReminderToggle(event) {
			const enabled = event.detail.value
			this.toggleReminder(enabled)
		},
		
		/**
		 * 提醒时间选择事件
		 */
		onReminderTimeChange(event) {
			const index = event.detail.value
			const minutes = this.reminderTimeOptions[index].value
			this.updateReminderTime(minutes)
		},
		

	}
}
</script>

<style lang="scss" scoped>
.schedule-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding-bottom: 80px;
}

// 状态栏
.status-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px 16px 16px;
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(10px);
	
	.app-title {
		display: flex;
		align-items: center;
		gap: 8px;
		
		.title-text {
			font-size: 18px;
			font-weight: 600;
			color: #FFFFFF;
		}
	}
	
	.status-info {
		.course-count {
			font-size: 12px;
			color: rgba(255, 255, 255, 0.8);
			background: rgba(255, 255, 255, 0.2);
			padding: 4px 8px;
			border-radius: 12px;
		}
	}
}

// 导入区域
.import-section {
	padding: 24px 16px;
}

.import-card {
	background: #FFFFFF;
	border-radius: 16px;
	padding: 32px 24px;
	box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.import-header {
	text-align: center;
	margin-bottom: 32px;
	
	.import-icon {
		margin-bottom: 16px;
	}
	
	.import-title {
		.title {
			display: block;
			font-size: 20px;
			font-weight: 600;
			color: #1F2937;
			margin-bottom: 8px;
		}
		
		.subtitle {
			font-size: 14px;
			color: #6B7280;
		}
	}
}

.simple-form {
	display: flex;
	flex-direction: column;
	gap: 16px;
	
	.input-wrapper {
		display: flex;
		align-items: center;
		background-color: #F9FAFB;
		border-radius: 8px;
		padding: 0 16px;
		height: 48px;
		border: 2px solid #E5E7EB;
		transition: all 0.2s ease;
		
		&:focus-within {
			border-color: #3B82F6;
			background-color: #FFFFFF;
		}
	}
	
	.simple-input {
		flex: 1;
		margin-left: 12px;
		font-size: 14px;
		color: #1F2937;
		background: transparent;
		border: none;
		outline: none;
		
		&::placeholder {
			color: #9CA3AF;
		}
		
		&:disabled {
			color: #9CA3AF;
			cursor: not-allowed;
		}
	}
	
	.simple-btn {
		width: 100%;
		padding: 14px;
		background: #3B82F6;
		color: #FFFFFF;
		border: none;
		border-radius: 8px;
		font-size: 14px;
		font-weight: 600;
		cursor: pointer;
		transition: all 0.2s ease;
		
		&:active {
			transform: scale(0.98);
			background: #2563EB;
		}
		
		&:disabled {
			background: #9CA3AF;
			cursor: not-allowed;
			transform: none;
		}
	}
}

// 课表内容
.schedule-content {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 50px); // 最小化预留空间，最大化课表显示区域
	padding: 0 16px 16px;
}

.week-navigation-compact {
		display: flex;
		justify-content: space-between;
		align-items: center;
	background: rgba(255, 255, 255, 0.95);
	backdrop-filter: blur(10px);
	border-radius: 12px;
	padding: 8px 16px;
	margin-bottom: 4px;
	flex-shrink: 0;
		
		.week-info {
			.week-title {
			font-size: 16px;
				font-weight: 600;
				color: #1F2937;
			margin-bottom: 2px;
			}
			
			.week-date {
			font-size: 11px;
				color: #6B7280;
			}
		}
		
		.nav-actions {
			display: flex;
			gap: 8px;
			
			.nav-btn {
				display: flex;
				align-items: center;
				justify-content: center;
			width: 32px;
			height: 32px;
				background: #F3F4F6;
				border: none;
			border-radius: 8px;
				transition: all 0.2s ease;
				
				&:active {
					transform: scale(0.95);
					background: #E5E7EB;
				}
				
				&:disabled {
					opacity: 0.5;
					cursor: not-allowed;
					transform: none;
				}
			}
		}
	}
	
// 课表网格 - 主要区域
.schedule-grid-main {
		display: flex;
	background: #FFFFFF;
	border-radius: 16px;
	overflow: hidden;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
	flex: 1;
	min-height: 0; // 允许flex收缩
	height: 600px; // 固定高度：头部60px + 12节课×45px = 600px
}

// 底部功能区域
.bottom-actions {
	flex-shrink: 0;
	margin-top: 4px;
	
	.action-buttons {
		display: flex;
		gap: 12px;
		justify-content: center;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 16px;
		padding: 16px;
		
		.action-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			gap: 0px;
			padding: 10px;
			border-radius: 12px;
			font-size: 11px;
			font-weight: 500;
			border: none;
			transition: all 0.2s ease;
			width: 55px;
			height: 55px;
			position: relative;
			
			&.primary {
				background: #3B82F6;
				color: #FFFFFF;
			}
			
			&.secondary {
				background: #F3F4F6;
				color: #6B7280;
			}
			
			&:active {
				transform: scale(0.95);
			}
			
			uni-icons {
				margin: 0px;
				padding: 0px;
				line-height: 1;
			}
			
			text {
				margin: 0px;
				margin-top: 2px;
				padding: 0px;
				line-height: 1;
			}
			
			.reminder-indicator {
				position: absolute;
				top: 6px;
				right: 6px;
				width: 12px;
				height: 12px;
				background: #FFFFFF;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
			}
		}
	}
}

.time-column {
	width: 70px;
	background: #F8FAFC;
	border-right: 1px solid #E2E8F0;
	height: 600px; // 固定高度：头部60px + 12节课×45px = 600px
	
	.time-header {
		height: 60px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 11px;
		font-weight: 600;
		color: #64748B;
		border-bottom: 1px solid #E2E8F0;
		background: #F1F5F9;
		position: sticky;
		top: 0;
		z-index: 2;
	}
	
	.time-slot {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-bottom: 1px solid #F1F5F9;
		
		.time-label {
			font-size: 10px;
			font-weight: 600;
			color: #475569;
		}
		
		.time-sub {
			font-size: 8px;
			color: #94A3B8;
			margin-top: 1px;
		}
	}
}

.days-container {
	flex: 1;
	height: 600px; // 与时间轴保持一致：头部60px + 12节课×45px = 600px
}

.days-wrapper {
	display: flex;
	width: 100%; // 占满剩余空间
}

.day-column {
	flex: 1;
	min-width: 0; // 允许压缩
	border-right: 1px solid #E2E8F0;
	
	&:last-child {
		border-right: none;
	}
	
	.day-header {
		height: 60px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #F8FAFC;
		border-bottom: 1px solid #E2E8F0;
		position: sticky;
		top: 0;
		z-index: 2;
		
		&.today {
			background: linear-gradient(135deg, #3B82F6, #1D4ED8);
			color: #FFFFFF;
			
			.day-name,
			.day-date {
				color: #FFFFFF;
			}
		}
		
		&.weekend {
			background: #FEF7F0;
			
			.day-name {
				color: #EA580C;
			}
		}
		
		.day-name {
			font-size: 11px;
			font-weight: 600;
			color: #475569;
			margin-bottom: 1px;
		}
		
		.day-date {
			font-size: 9px;
			color: #64748B;
		}
		
		.day-indicator {
			position: absolute;
			bottom: 4px;
			width: 4px;
			height: 4px;
			background: #FFFFFF;
			border-radius: 50%;
		}
	}
	
	.day-content {
		height: 540px; // 内容区域高度：12节课×45px = 540px（不含头部）
		position: relative;
		
		.time-slot-content {
			position: relative;
			border-bottom: 1px solid #E2E8F0;
			
			&:last-child {
				border-bottom: none;
			}
			
			// 特殊时间段的样式
			&:nth-child(4) { // 第4节课后 - 午休时间（id: 3）
				border-bottom: 2px solid #CBD5E1;
			}
			
			&:nth-child(9) { // 第9节课后 - 晚饭时间（id: 8）
				border-bottom: 2px solid #CBD5E1;
			}
		}
		
		.course-item {
			padding: 2px 4px;
			border-radius: 4px;
			cursor: pointer;
			transition: all 0.2s ease;
			overflow: hidden;
			
			&:active {
				transform: scale(0.98);
			}
			
			&.spanning-course {
				border-radius: 6px;
				padding: 4px 6px;
			
			.course-title {
					font-size: 11px;
					font-weight: 700;
					word-wrap: break-word;
					word-break: break-all;
					line-height: 1.1;
				}
			}
			
			.course-header {
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				margin-bottom: 1px;
				
				.span-indicator {
					background: rgba(255, 255, 255, 0.3);
					border-radius: 50%;
					width: 14px;
					height: 14px;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-shrink: 0;
					margin-left: 4px;
				}
			}
			
			.course-title {
				font-size: 9px;
				font-weight: 600;
				color: #1F2937;
				line-height: 1.1;
				flex: 1;
				word-wrap: break-word;
				word-break: break-all;
			}
			
			.course-time {
				font-size: 7px;
				color: #6B7280;
				margin-bottom: 1px;
			}
			
			.course-duration {
				font-size: 7px;
				color: #FFFFFF;
				background: rgba(0, 0, 0, 0.2);
				padding: 1px 4px;
				border-radius: 8px;
				display: inline-block;
				margin-bottom: 1px;
			}
			
			.course-location {
				display: flex;
				align-items: center;
				gap: 1px;
				margin-bottom: 1px;
				
				text {
					font-size: 7px;
					color: #9CA3AF;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
			
			.course-teacher {
				font-size: 7px;
				color: #9CA3AF;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
		
		.empty-day {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: #9CA3AF;
			
			text {
				font-size: 11px;
				margin-top: 6px;
			}
		}
	}
}

// 弹窗样式
.course-detail-modal,
.settings-modal {
	background: #FFFFFF;
	border-radius: 16px;
	max-height: 80vh;
	
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20px 20px 16px;
		border-bottom: 1px solid #E5E7EB;
		
		.modal-title {
			font-size: 18px;
			font-weight: 600;
			color: #1F2937;
		}
		
		.close-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 32px;
			height: 32px;
			background: #F3F4F6;
			border: none;
			border-radius: 8px;
			transition: all 0.2s ease;
			
			&:active {
				transform: scale(0.95);
				background: #E5E7EB;
			}
		}
	}
}

.course-details {
	padding: 20px;
	
	.detail-row {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16px;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.detail-icon {
			width: 32px;
			height: 32px;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #F3F4F6;
			border-radius: 8px;
			margin-right: 12px;
		}
		
		.detail-content {
			flex: 1;
			
			.detail-label {
				display: block;
				font-size: 12px;
				color: #6B7280;
				margin-bottom: 4px;
			}
			
			.detail-value {
				font-size: 14px;
				color: #1F2937;
				font-weight: 500;
			}
		}
	}
}

.settings-content {
	padding: 20px;
	
	.setting-section {
		margin-bottom: 24px;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.section-title {
			display: block;
			font-size: 16px;
			font-weight: 600;
			color: #1F2937;
			margin-bottom: 16px;
			padding-bottom: 8px;
			border-bottom: 1px solid #E5E7EB;
		}
	}
	
	.setting-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.setting-info {
			flex: 1;
			
			.setting-label {
				display: block;
				font-size: 14px;
				color: #374151;
				font-weight: 500;
				margin-bottom: 2px;
			}
			
			.setting-desc {
				font-size: 12px;
				color: #6B7280;
			}
		}
		
		.setting-label {
			font-size: 14px;
			color: #374151;
			font-weight: 500;
		}
		
		.setting-btn {
			display: flex;
			align-items: center;
			gap: 6px;
			padding: 8px 12px;
			border-radius: 8px;
			border: none;
			font-size: 12px;
			font-weight: 500;
			transition: all 0.2s ease;
			
			&.primary {
				background: #3B82F6;
				color: #FFFFFF;
			}
			
			&.secondary {
				background: #F3F4F6;
				color: #374151;
			}
			
			&.danger {
				background: #EF4444;
				color: #FFFFFF;
			}
			
			&:active {
				transform: scale(0.95);
			}
		}
		
		switch {
			transform: scale(0.8);
		}
		
		picker {
			button {
				background: transparent;
				border: none;
				padding: 0;
			}
		}
	}
}

// 动画
@keyframes spin {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

// 响应式适配
@media (max-width: 480px) {
	.schedule-content {
		padding: 0 8px 4px;
		height: calc(100vh - 40px); // 最大化可用高度
	}
	
	.week-navigation-compact {
		padding: 6px 12px;
		margin-bottom: 4px;
		
		.week-info {
			.week-title {
				font-size: 14px;
			}
			
			.week-date {
				font-size: 10px;
			}
		}
		
		.nav-btn {
			width: 28px;
			height: 28px;
		}
	}
	
	.schedule-grid-main {
		font-size: 90%;
		height: 540px; // 移动端：头部50px + 12节课×40.8px ≈ 540px
	}
	
	.time-column {
		width: 55px;
		height: 540px; // 移动端时间轴：头部50px + 12节课×40.8px ≈ 540px
		
		.time-header {
			height: 50px;
			font-size: 10px;
		}
	}
	
	.days-container {
		height: 540px; // 移动端日期容器：与时间轴保持一致
	}
	
	.day-column {
		.day-header {
			height: 50px;
			
			.day-name {
				font-size: 10px;
			}
			
			.day-date {
				font-size: 8px;
			}
		}
	}
	
	.day-content {
		height: 490px; // 移动端内容区域：12节课×40.8px ≈ 490px（不含头部50px）
	}
	
	.bottom-actions {
		margin-top: 4px;
		
		.action-buttons {
			gap: 8px;
			padding: 12px;
			
			.action-btn {
				padding: 8px;
				width: 50px;
				height: 50px;
				font-size: 10px;
				
				text {
					font-size: 10px;
				}
			}
		}
	}
	
	.course-item {
		padding: 1px 2px !important;
		
		.course-title {
			font-size: 8px !important;
		}
		
		.course-time,
		.course-location text,
		.course-teacher {
			font-size: 6px !important;
		}
	}
}
</style> 